package cn.itcast.service.impl;

import cn.itcast.entity.ShoppingCart;
import cn.itcast.mapper.IShoppingCartMapper;
import cn.itcast.service.IShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class ShoppingCartServiceImpl implements IShoppingCartService {
    @Autowired
    private IShoppingCartMapper shoppingCartMapper;
    @Override
    public ShoppingCart add(ShoppingCart shoppingCart) {
        shoppingCart.setCreateTime(LocalDateTime.now());
        ShoppingCart dBShoppingCart = shoppingCartMapper.findByDishIdOrSetMealId(shoppingCart);
        if (dBShoppingCart != null) {
            dBShoppingCart.setNumber(dBShoppingCart.getNumber()+1);
            shoppingCartMapper.updateNum(dBShoppingCart);
            return dBShoppingCart;
        }
        shoppingCart.setNumber(1);
        shoppingCartMapper.add(shoppingCart);
        return shoppingCart;
    }

    @Override

    public ShoppingCart sub(ShoppingCart shoppingCart) {
        log.error("shopingCart"+shoppingCart);
        ShoppingCart dBShoppingCart = shoppingCartMapper.findByDishIdOrSetMealId(shoppingCart);
        log.info("dbShoping====={}",dBShoppingCart);
        if (dBShoppingCart.getNumber()>1) {
            dBShoppingCart.setNumber(dBShoppingCart.getNumber()-1);
            shoppingCartMapper.updateNum(dBShoppingCart);
            return dBShoppingCart;
        }

            shoppingCartMapper.remove(dBShoppingCart);
            dBShoppingCart.setNumber(0);


        return dBShoppingCart;
    }

    @Override
    public List<ShoppingCart> list(Long userId) {
        return shoppingCartMapper.list( userId);
    }

    @Override
    public void clean(Long userId) {
        shoppingCartMapper.clean(userId);
    }


}
